package utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * This is a class to convert BEAT output files to XML format
 * */
public class XMLGeneration {

	HashMap<String,ArrayList<String>> conceptMap;
	/**
	 * Main class to run the conversion.
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
//		XMLGeneration p = new XMLGeneration();
//		List<BeatAnn> annotationList = p.parseDSInputFile("inputfiles\\karen\\annotations.tsv");
//		//p.CreateXMLFilesforDS("outputfiles\\karen\\", annotationList, "k" );
//		p.CreateXMLFilesforDS2("outputfiles\\karen\\", annotationList, "k" );
//		System.out.println("Karen's Task Completed for Daily Strength!!");
//		
//		List<String> twitterannList = p.parseTwitterFile("inputfiles\\karen\\binaryannotations.tsv");
//		p.CreateXMLFilesforTwitter("twitterOutputfiles\\karen\\", twitterannList, "k");
//		System.out.println("Karen's Task completed for Twitter!!");
//		
//		annotationList = p.parseDSInputFile("inputfiles\\robert\\annotations.tsv");
//		//p.CreateXMLFilesforDS("outputfiles\\robert\\", annotationList, "r" );
//		p.CreateXMLFilesforDS2("outputfiles\\robert\\", annotationList, "r");
//		System.out.println("Robert's Task Completed for Daily Strength!!");
//		
//		twitterannList = p.parseTwitterFile("inputfiles\\robert\\binaryannotations.tsv");
//		p.CreateXMLFilesforTwitter("twitterOutputfiles\\robert\\", twitterannList, "r");
//		System.out.println("Robert's Task completed for Twitter!!");
	}
	
	/**
	 * Method to get the concept name for concept id
	 * */
	private void getConceptName(){
		//String conceptName = null;
		conceptMap = new HashMap<String, ArrayList<String>>();
		try{
			File conceptFile = new File("inputfiles\\conceptNames.tsv");
			if(conceptFile.exists())
			{
				BufferedReader reader = new BufferedReader(new FileReader(conceptFile));
				String line;
				while((line=reader.readLine())!=null){
					String[] splitdata = line.split("\t");
					if(splitdata.length == 2){
						if(!conceptMap.containsKey(splitdata[0])){
							ArrayList<String> list = new ArrayList<String>();
							list.add(splitdata[1]);
							conceptMap.put(splitdata[0], list);
						}
						else
						{
							ArrayList<String> list = conceptMap.get(splitdata[0]);
							list.add(splitdata[1]);
							conceptMap.put(splitdata[0], list);
						}
					}
				}
				reader.close();
			}
			else
			{
				System.out.println("Problem in Loading concept file");
				return ;
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
		//return conceptName;
	}

	/*
	 * Method to parse the input BEAT files
	 * */
	private List<BeatAnn> parseDSInputFile(File file){//String path){
		List<BeatAnn> annotationsList = new ArrayList<BeatAnn>();
		
		try{
			
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line;
			while((line = reader.readLine())!= null)
			{
				String[] splitdata = line.split("\t");
				
				if(splitdata.length == 8 || splitdata.length == 9)
				{
					BeatAnn obj = new BeatAnn();
					obj.annid = splitdata[0];
					obj.start = Integer.parseInt(splitdata[1]) + 1;
					obj.end = Integer.parseInt(splitdata[2]) + 1;
					obj.annType = splitdata[3];
					obj.conceptId = splitdata[4];
					if(conceptMap.containsKey(obj.conceptId))
					{
						String conceptnames = "";
						ArrayList<String> list = conceptMap.get(obj.conceptId);
						for(int i=0;i<list.size();i++){
							if(conceptnames.equals(""))
							{
								conceptnames = list.get(i);
							}
							else
							{
								conceptnames = conceptnames + ", " + list.get(i);
							}
						}
						obj.conceptName = conceptnames;
					}
					else
						obj.conceptName = "";
					obj.text = splitdata[5];
					obj.relatedDrug = splitdata[6];
					obj.targetDrug = splitdata[7];
					if(splitdata.length == 9)
						obj.c_level = splitdata[8];
					else
						obj.c_level = "3";
					annotationsList.add(obj);
				}
			}
			reader.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return annotationsList;
	}
	
	/*
	 * Method to convert the BEAT output file into XML format and store it in a folder
	 * */
//	private void CreateXMLFilesforDS(String folderPath, List<BeatAnn> inputList, String inifilename){
//		try{
//			HashMap<String,String> map = MapText("inputfiles\\DStexts.tsv");
//			
//			HashMap<String,HashMap<String,Integer>> countHash = new HashMap<String,HashMap<String,Integer>>();
//			
//			BufferedWriter writer = null;
//			for(BeatAnn objbeatann : inputList){
//				String path = folderPath + inifilename + "_" + objbeatann.annid +".xml";
//				File file = new File(path);
//				
//				
//				if(!file.exists())
//				{
//					file.createNewFile();
//					writer = new BufferedWriter(new FileWriter(path,true));
//					writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<DSAdverseDrugReactions> \n<TEXT><![CDATA[\n");
//					writer.append(map.get(objbeatann.annid));
//					writer.append("\n]]></TEXT>\n");
//					writer.append("<TAGS>\n");
//				}
//				else
//				{
//					writer = new BufferedWriter(new FileWriter(path,true));
//				}
//				
//				String id;
//				if(countHash.containsKey(objbeatann.annid))
//				{
//					HashMap<String,Integer> innerHash = countHash.get(objbeatann.annid);
//					int count = (innerHash.get(objbeatann.annType) + 1);
//					id = objbeatann.annType + "" + count;
//					innerHash.put(objbeatann.annType, count);
//					countHash.put(objbeatann.annid, innerHash);
//				}
//				else 
//				{
//					HashMap<String,Integer> innerHash = new HashMap<String, Integer>();
//					innerHash.put("ADR", 0);
//					innerHash.put("Beneficial", 0);
//					innerHash.put("Other", 0);
//					innerHash.put("Indication", 0);
//					innerHash.put("Drug", 0);
//					innerHash.put("Interaction", 0);
//					countHash.put(objbeatann.annid, innerHash);
//					int count = (innerHash.get(objbeatann.annType) + 1);
//					id = objbeatann.annType + "" + count;
//					innerHash.put(objbeatann.annType, count);
//					countHash.put(objbeatann.annid, innerHash);
//				}
//				
//				writer.append("<" + objbeatann.annType + " id=\"" + id +"\" start=\"" + objbeatann.start	+ "\" end=\"" + 
//				objbeatann.end + "\" text=\"" + objbeatann.text + "\" conceptID=\"" + objbeatann.conceptId + 
//				"\" relatedDrug=\"" + objbeatann.relatedDrug + "\" targetDrug=\"" + objbeatann.targetDrug  +"\" />");
//				writer.append("\n");
//				writer.close();
//			}
//			 
//		  //String files;
//		  File folder = new File(folderPath);
//		  File[] listOfFiles = folder.listFiles(); 
//		  for (int i = 0; i < listOfFiles.length; i++) 
//		  {
//			   if (listOfFiles[i].isFile()) 
//			   {
//				   //files = listOfFiles[i].getName();
//				   writer = new BufferedWriter(new FileWriter(folderPath + listOfFiles[i].getName(),true));
//				   writer.append("</TAGS>\n</DSAdverseDrugReactions>\n");
//				   writer.close();
//				   //System.out.println(files);
//			   }
//		  }
//		  
//		}catch(Exception ex){
//			ex.printStackTrace();
//		}
//	}
	
	/*
	 * Method to convert the BEAT output file into XML format type 2....
	 * */
	public String CreateXMLFilesforDS2(File inputfile,File inputTextFile, File outputDir){
		String result;
		getConceptName();
 		List<BeatAnn> inputList = parseDSInputFile(inputfile);
		try{
			HashMap<String,String> map = MapText(inputTextFile);
			
			//HashMap<String,HashMap<String,Integer>> countHash = new HashMap<String,HashMap<String,Integer>>();
			
			BufferedWriter writer = null;
			int count = 0;
			for(BeatAnn objbeatann : inputList){
				String path = outputDir.getPath() + "\\" + outputDir.getName() + "_" + objbeatann.annid +".xml";
				File file = new File(path);
				
				if(!file.exists())
				{
					file.createNewFile();
					writer = new BufferedWriter(new FileWriter(path,true));
					writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<DSAdverseDrugReactions> \n<TEXT><![CDATA[\n");
					writer.append(map.get(objbeatann.annid));
					writer.append("\n]]></TEXT>\n");
					writer.append("<TAGS>\n");
				}
				else
				{
					writer = new BufferedWriter(new FileWriter(path,true));
				}
				
				int level = Integer.parseInt(objbeatann.c_level);
				String confLevel = "";
				if(level == 3)
					confLevel = "High";
				else if(level == 2 )
					confLevel = "Moderate";
				else if(level == 1)
					confLevel = "Low";
				
				writer.append("<Annotation id=\"id" + count +"\" start=\"" + objbeatann.start	+ "\" end=\"" + 
				objbeatann.end + "\" text=\"" + objbeatann.text + "\" type=\"" + objbeatann.annType +"\" conceptID=\"" + objbeatann.conceptId + 
				"\" conceptName=\"" + objbeatann.conceptName + "\" relatedDrug=\"" + objbeatann.relatedDrug + "\" targetDrug=\"" + 
				objbeatann.targetDrug  +"\" confidence=\"" + confLevel +"\" />");
				writer.append("\n");
				writer.close();
				count++;
			}
			 
		  //String files;
		  File folder = new File(outputDir.getPath());
		  File[] listOfFiles = folder.listFiles(); 
		  for (int i = 0; i < listOfFiles.length; i++) 
		  {
			   if (listOfFiles[i].isFile()) 
			   {
				   //files = listOfFiles[i].getName();
				   writer = new BufferedWriter(new FileWriter(outputDir.getPath() + "\\" + listOfFiles[i].getName(),true));
				   writer.append("</TAGS>\n</DSAdverseDrugReactions>\n");
				   writer.close();
				   //System.out.println(files);
			   }
		  }
		  
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		result = "XML files created!!!!";
		
		return result;
	}
	
	/*
	 * Method to map the input annotations 
	 * */
	private HashMap<String,String> MapText(File file){
		HashMap<String,String> map = new HashMap<String,String>();
		try{
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line;
			while((line = reader.readLine())!= null){
				String[] splitdata = line.split("\t");
				if(splitdata.length == 2)
				{
					map.put(splitdata[0].trim(), splitdata[1].trim());
				}
			}
			reader.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return map;
	}

	/*
	 * Method to parse the annotated input file for Twitter data 
	 * */
	private List<String> parseTwitterFile(File file)
	{
		List<String> binaryannList = new ArrayList<String>();
		try{
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line;
			while((line=reader.readLine())!=null){
				if(line.split("\t").length == 2){
					binaryannList.add(line);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return binaryannList;
	}//twitterOutputfiles

	/*
	 * Method to convert the BEAT output file into XML format and store it in a folder
	 * */
	public String CreateXMLFilesforTwitter(File inputfile, File inputTextfile, File outputDir){
		
		List<String> binaryinputList = parseTwitterFile(inputfile);
		
		HashMap<String,String> map = MapText(inputTextfile);
		try
		{
			for(String line : binaryinputList){
				String[] splitdata = line.split("\t");
				
				if(map.containsKey(splitdata[0].trim()))
				{
					BufferedWriter writer = new BufferedWriter(new FileWriter(outputDir.getPath() + "\\"+ outputDir.getName() + "_" + splitdata[0]+".xml"));
					writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<TwitterAdverseDrugReactions> \n<TEXT><![CDATA[\n");
					writer.append(map.get(splitdata[0].trim()));
					writer.append("\n]]></TEXT>\n");
					writer.append("<TAGS>\n");
					
					writer.append("<ELE id=\"1\" start=\"1\" end=\"" + ((map.get(splitdata[0].trim())).length() + 1) + 
							"\" text=\"" + map.get(splitdata[0].trim()) + "\" type=\"" + splitdata[1] +"\" />");
					
					writer.append("\n</TAGS>\n</TwitterAdverseDrugReactions>\n");
					writer.close();
				}
				else
				{
					System.out.println("Error in input files");
					return "";
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return "XML file conversion completed!!!";
	}
	
}
